package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName NioTestTwoo.java
 * @Description TODO
 * @createTime 2020年04月28日 20:47:00
 */
public class NioTestTwo {
	public static void main(String[] args) throws Exception {
		int[] ports = new int[5];
		ports[0] = 5001;
		ports[1] = 5001;
		ports[2] = 5002;
		ports[3] = 5003;
		ports[4] = 5004;
		//创建一个selector
		Selector selector = Selector.open();
		for (int i = 0; i < ports.length; i++) {
			//获取一个channel
			ServerSocketChannel socketChannel = ServerSocketChannel.open();
			//设置为非阻塞模式
			socketChannel.configureBlocking(false);
			ServerSocket socket = socketChannel.socket();
			InetSocketAddress socketAddress = new InetSocketAddress(ports[i]);
			socket.bind(socketAddress);
			//将channel注册到给定的selector的selectKey中
			socketChannel.register(selector, SelectionKey.OP_ACCEPT);
			System.out.println("监听端口：" + ports[i]);
		}
		while (true) {
			int numbers = selector.select();
			System.out.println("numbers：" + numbers);
			//获取selector的selectKey
			Set<SelectionKey> keys = selector.selectedKeys();
			System.out.println("selectKeys：" + keys);
			Iterator<SelectionKey> iterator = keys.iterator();
			while (iterator.hasNext()) {
				SelectionKey next = iterator.next();
				if (next.isAcceptable()) {
					ServerSocketChannel channel = (ServerSocketChannel) next.channel();
					SocketChannel socketChannel = channel.accept();
					socketChannel.configureBlocking(false);
					socketChannel.register(selector, SelectionKey.OP_READ);

					System.out.println("获取客户端连接：" + socketChannel);
				} else if (next.isReadable()) {
					SocketChannel channel = (SocketChannel) next.channel();
					int bytesRead = 0;
					while (true) {
						ByteBuffer byteBuffer = ByteBuffer.allocate(512);
						byteBuffer.clear();
						int read = channel.read(byteBuffer);
						if (read <= 0) {
							break;
						}
						byteBuffer.flip();
						channel.write(byteBuffer);
						bytesRead += read;
					}
				}
				iterator.remove();
			}
		}
	}
}
